<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="adDialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 添加type="expand"就行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom','vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环 嵌套渲染二级权限 -->
                <el-row v-for="item2 in item1.children" :key="item2.id" :class="['vcenter']">
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre></pre>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="EditDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deleteUserById(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="small"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose"
    >
      <!-- 树形控件 :data="rightsList"数据源 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="adDialogVisible" width="50%" @close="addJsDialogClose">
      <el-form :model="addJsForm" :rules="addJsFormRules" ref="addJsFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addJsForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addJsForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addJSUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editJsDialogVisible" width="50%" @close="editJsDialogClose">
      <el-form :model="editJsForm" :rules="editJsFormRules" ref="editJsFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editJsForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editJsForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editJsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="cfEditJSUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolesList: [],
      //   控制分配权限展示与隐藏
      setRightDialogVisible: false,
      //   添加角色 展示与隐藏
      adDialogVisible: false,
      // 角色编辑  展示与隐藏
      editJsDialogVisible: false,
      //   添加角色表单数据
      addJsForm: {
        roleName: '',
        roleDesc: ''
      },
      //  添加角色 验证规则对象
      addJsFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3-10个字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '用户名的长度在3-20个字符之间',
            trigger: 'blur'
          }
        ]
      },
      // 获取到当前行 角色编辑信息列表
      editJsForm: {},
      editJsFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3-10个字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '用户名的长度在3-20个字符之间',
            trigger: 'blur'
          }
        ]
      },
      //   所有权限得数据
      rightsList: [],
      //   树形控件绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //   默认选中得节点id值数组
      defKeys: [],
      //   当前即将分配权限得角色ID
      roleId: ''
    }
  },
  created() {
    this.getRolesLise()
  },
  methods: {
    async getRolesLise() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    //   根据id删除对应得权限
    async removeRightById(role, rightId) {
      //  弹框用户是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      //  this.getRolesLise()  会重新渲染页面导致列表关上
      role.children = res.data
    },
    // 展示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有分配权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分配权限列表失败')
      }
      //   把获取到得权限数据 保存到data中
      this.rightsList = res.data
      console.log(this.rightsList)
      //   递归获取三级节点得ID
      this.getLeafKeys(role, this.defKeys)

      this.setRightDialogVisible = true
    },
    // 通过递归形式 获取角色下所有三级权限id 并保存到defKE样式数组中
    getLeafKeys(node, arr) {
      // 如果当前node节点不包含childern属性 则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 监听分配权限对话框关闭 重置数据
    setRightDialogClose() {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesLise()
      this.setRightDialogVisible = false
    },

    // 监听添加角色对话框的关闭事件   resetFields ui表单重置函数  对话框输入错误或者未输入提示得警告框 关闭后再打开还会有 用resetF 关闭后就不会有了
    addJsDialogClose() {
      this.$refs.addJsFormRef.resetFields()
    },
    // 点击确认按钮 添加新角色
    addJSUser() {
      this.$refs.addJsFormRef.validate(async vali => {
        console.log(vali) //validate 与验证 填写正确拿到true 错误是false
        if (!vali) return //如果vali校验失败 就return出去
        // 没失败 就可以发起添加角色请求
        const { data: res } = await this.$http.post(`roles`, this.addJsForm) //用户信息可以用对象形式传送过去  用户信息就是this.addJsForm
        if (res.meta.status !== 201) {
          this.$message.error('添加失败')
        }
        this.$message.success('添加角色成功')
        // 隐藏添加用户对话框
        this.adDialogVisible = false
        //重新获取表单
        this.getRolesLise()
      })
    },
    // 根据scope row当前行的ID 删除当前行角色数据
    async deleteUserById(id) {
      const confirmJsResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.log(confirmJsResult) //取消可以获得cancel  确认可以获得confirm
      if (confirmJsResult !== 'confirm') {
        return this.$message.error('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/` + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      q
      this.$message.success('删除用户成功')
      //   重新获取表单页面
      this.getRolesLise()
    },
    // 查询当前行的角色编辑信息
    async EditDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      //    console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('获取当前行角色信息失败')
      }
      this.editJsForm = res.data
      this.editJsDialogVisible = true
    },
editJsDialogClose(){
    this.$refs.editJsFormRef.resetFields()
},
    // 修改查询到的角色信息
    cfEditJSUser() {
      this.$refs.editJsFormRef.validate(async vali => {
        if (!vali) return
        // 校验成功 发起修改角色信息请求
        const { data: res } = await this.$http.put(
          'roles/' + this.editJsForm.roleId,
          {
            roleName: this.editJsForm.roleName,
            roleDesc: this.editJsForm.roleDesc
          }
        )


        if (res.meta.status !== 200) {
          return this.$message.error('编辑角色失败')
        }

        this.$message.success('编辑角色成功')
        this.editJsDialogVisible = false
        this.getRolesLise()
      })
    }
  }
}
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>


